<template>
  <nav-bar />
  <view class="inventory-detail-page">
    <!-- 顶部导航 -->
    <view class="nav-bar">
      <text class="nav-back" @click="onBack">&#8592;</text>
      <text class="nav-title">盘点明细</text>
      <view class="action-bar">
        <button class="action-btn" type="primary" size="mini" @click="onAddDetailClick">
          <uni-icons type="plusempty" size="18" color="#fff" style="margin-right:6rpx" />添加明细
        </button>
        <!-- 预留：后续可添加更多按钮 -->
      </view>
    </view>

    <!-- 主盘点ID展示区 -->
    <view class="main-inventory-id-bar">
      <text class="main-id-label">主盘点ID：</text>
      <text class="main-id-value" :title="inventoryId">{{ inventoryId }}</text>
      <!-- <uni-icons type="copy" size="20" color="#1890ff" class="copy-icon" @click="copyInventoryId" /> -->
      <text class="iconfont icon-copy" style="font-size: 20px; color: #1890ff;" @click="copyInventoryId"></text>
    </view>

    <!-- 搜索和筛选区域 -->
    <view class="search-filter">
      <view class="search-box">
        <uni-icons type="search" size="20" color="#999"></uni-icons>
        <input 
          class="search-input" 
          v-model="searchKeyword" 
          placeholder="搜索商品名称"
          @input="onSearch"
        />
      </view>
      <view class="filter-box">
        <picker 
          class="filter-picker" 
          :range="filterOptions" 
          range-key="label"
          @change="onFilterChange"
        >
          <view class="picker-value">
            <text>{{ currentFilter?.label || '' }}</text>
            <uni-icons type="bottom" size="14" color="#999"></uni-icons>
          </view>
        </picker>
      </view>
    </view>

    <!-- 统计信息 -->
    <view class="statistics">
      <view class="stat-card">
        <view class="stat-icon total">
          <uni-icons type="gift" size="24" color="#1890ff"></uni-icons>
        </view>
        <view class="stat-content">
          <text class="stat-value">{{ filteredDetails?.length || 0 }}</text>
          <text class="stat-label">总商品数</text>
        </view>
      </view>
      <view class="stat-card">
        <view class="stat-icon difference">
          <!-- <uni-icons type="warning" size="24" color="#ff4d4f"></uni-icons> -->
          <text class="iconfont icon-difference" style="font-size: 24px; color: #ff4d4f;"></text>
        </view>
        <view class="stat-content">
          <text class="stat-value difference">{{ differenceCount }}</text>
          <text class="stat-label">有差异</text>
        </view>
      </view>
    </view>

    <!-- 明细列表 -->
    <scroll-view 
      class="detail-list"
      scroll-y
      :scroll-top="scrollTop"
      @scroll="onScroll"
    >
      <view 
        class="detail-item" 
        v-for="detail in visibleDetails" 
        :key="detail.id"
        :style="{ height: itemHeight + 'px' }"
        @click="onShowDetail(detail)"
      >
        <view class="item-content">
          <view class="item-header">
            <view class="product-info">
              <text class="product-name">{{ detail.product_name }}</text>
              <text class="product-id">ID: {{ detail.id }}</text>
            </view>
            <text class="difference-tag" :class="getDifferenceClass(detail.inventory_difference_number)">
              {{ getDifferenceText(detail.inventory_difference_number) }}
            </text>
          </view>
          <view class="item-info">
            <view class="info-row">
              <view class="info-item">
                <text class="info-label">预计数量</text>
                <text class="info-value">{{ detail.inventory_number }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">实际数量</text>
                <text class="info-value">{{ detail.inventory_actual_number }}</text>
              </view>
            </view>
            <view class="info-row" v-if="detail.inventory_difference_number !== 0">
              <view class="info-item full-width">
                <text class="info-label">差异原因</text>
                <text class="info-value reason">{{ detail.inventory_difference_reason || '暂无原因' }}</text>
              </view>
            </view>
            <view class="info-row" v-if="detail.remark">
              <view class="info-item full-width">
                <text class="info-label">备注</text>
                <text class="info-value reason remark-ellipsis" :class="{expanded: expandedRemarkId === detail.id}" @click.stop="toggleRemark(detail.id)">
                  {{ getRemarkText(detail) }}
                  <text v-if="shouldShowToggle(detail)" class="remark-toggle">{{ expandedRemarkId === detail.id ? '收起' : '展开' }}</text>
                </text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 添加明细弹窗（手写） -->
    <view v-if="showAddDetailPopup" class="custom-popup-mask" @click.self="closeAddDetailPopup">
      <view class="custom-popup-box">
        <view class="popup-header">
          <text class="popup-title">添加盘点明细</text>
          <uni-icons type="closeempty" size="22" color="#999" @click="closeAddDetailPopup" />
        </view>
        <view class="popup-content">
          <!-- 商品选择按钮 -->
          <view class="form-row">
            <text class="form-label">商品</text>
            <view class="form-input select-btn" @click="showProductSelectPopup = true">
              <text v-if="selectedProduct" class="selected-product-name">{{ selectedProduct.name }}</text>
              <text v-else class="placeholder">请选择商品</text>
              <uni-icons type="bottom" size="18" color="#999" style="margin-left:8rpx" />
            </view>
          </view>
          <view class="form-row">
            <text class="form-label">预计数量</text>
            <input class="form-input" v-model.number="addDetailForm.inventory_number" type="number" placeholder="请输入预计数量" @input="onInputChange" />
          </view>
          <view class="form-row">
            <text class="form-label">实际数量</text>
            <input class="form-input" v-model.number="addDetailForm.inventory_actual_number" type="number" placeholder="请输入实际数量" @input="onInputChange" />
          </view>
          <view class="form-row">
            <text class="form-label">差异数量</text>
            <input class="form-input" :value="addDetailForm.inventory_difference_number" disabled style="background:#f5f5f5;color:#999;" />
          </view>
          <view class="form-row" v-if="addDetailForm.inventory_difference_number !== 0">
            <text class="form-label">差异原因</text>
            <input class="form-input" v-model="addDetailForm.inventory_difference_reason" placeholder="如无差异可不填" />
          </view>
          <view class="form-row">
            <text class="form-label">备注</text>
            <input class="form-input" v-model="addDetailForm.remark" placeholder="可选" />
          </view>
        </view>
        <view class="popup-footer">
          <button class="confirm-btn" type="primary" @click="onAddDetail">确定</button>
          <button class="cancel-btn" @click="closeAddDetailPopup">取消</button>
        </view>
      </view>
    </view>

    <!-- 商品选择弹窗 -->
    <view v-if="showProductSelectPopup" class="custom-popup-mask" @click.self="closeProductSelectPopup">
      <view class="product-popup-box">
        <view class="popup-header">
          <text class="popup-title">选择商品</text>
          <uni-icons type="closeempty" size="22" color="#999" @click="closeProductSelectPopup" />
        </view>
        <view class="popup-content">
          <view class="product-search-bar">
            <uni-icons type="search" size="28" color="#bbb" class="search-icon" />
            <input class="product-search-input" v-model="productSearch" placeholder="搜索商品名称" />
          </view>
          <scroll-view class="product-list-scroll" scroll-y>
            <view v-for="item in filteredProductList" :key="item.id" class="product-item-big" @click="onSelectProduct(item)">
              <image v-if="item.images && item.images.length > 0" :src="IntranetConfig.domain + item.images[0].image" class="product-img" mode="aspectFill" />
              <view v-else class="product-img product-img-placeholder">
                <uni-icons type="photo" size="48" color="#ccc" />
              </view>
              <text class="product-name-big">{{ item.name }}</text>
            </view>
            <view v-if="filteredProductList.length === 0" class="no-result">无匹配商品</view>
          </scroll-view>
        </view>
      </view>
    </view>

    <!-- 自定义消息框组件 -->
    <message-box
      v-model="showMsgBox"
      :title="msgBoxTitle"
      :content="msgBoxContent"
      :showCancel="msgBoxShowCancel"
      :confirmText="msgBoxConfirmText"
      :cancelText="msgBoxCancelText"
      @confirm="onMsgBoxConfirm"
      @cancel="onMsgBoxCancel"
    />

    <!-- 自定义 Toast 组件 -->
    <toast
      v-model="showToast"
      :content="toastContent"
      :type="toastType"
      :duration="toastDuration"
    />

    <!-- 明细详情弹窗 -->
    <view v-if="showDetailPopup" class="custom-popup-mask" @click.self="closeDetailPopup">
      <view class="custom-popup-box detail-popup-box">
        <view class="popup-header">
          <text class="popup-title">明细详情</text>
          <uni-icons type="closeempty" size="22" color="#999" @click="closeDetailPopup" />
        </view>
        <view class="popup-content detail-popup-content">
          <view class="detail-row"><text class="detail-label">商品：</text><text class="detail-value">{{ currentDetail.product_name }}</text></view>
          <view class="detail-row"><text class="detail-label">预计数量：</text><text class="detail-value">{{ currentDetail.inventory_number }}</text></view>
          <view class="detail-row"><text class="detail-label">实际数量：</text><text class="detail-value">{{ currentDetail.inventory_actual_number }}</text></view>
          <view class="detail-row"><text class="detail-label">差异数量：</text><text class="detail-value">{{ currentDetail.inventory_difference_number }}</text></view>
          <view class="detail-row"><text class="detail-label">差异原因：</text><text class="detail-value">{{ currentDetail.inventory_difference_reason || '无' }}</text></view>
          <view class="detail-row"><text class="detail-label">备注：</text><text class="detail-value">{{ currentDetail.remark || '无' }}</text></view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { IntranetConfig } from '@/static/js/config'
import MessageBox from '@/components/message-box/message-box.vue'
import Toast from '@/components/toast/toast.vue'
import { onLoad } from '@dcloudio/uni-app'

// 支持id作为props，解决Extraneous non-props attributes (id)警告
const props = defineProps({
  id: [String, Number]
})

// 路由参数
const inventoryId = ref('')

// 搜索和筛选相关
const searchKeyword = ref('')
const filterOptions = [
  { value: 'all', label: '全部' },
  { value: 'difference', label: '有差异' },
  { value: 'no-difference', label: '无差异' }
]
const currentFilter = ref(filterOptions[0])

// 虚拟列表相关
const itemHeight = 180 // 每个项目的高度
const visibleCount = 10 // 可视区域显示的项目数量
const scrollTop = ref(0)
const startIndex = ref(0)

// 盘点明细数据
const detailList = ref([])

// 计算过滤后的明细列表
const filteredDetails = computed(() => {
  let result = detailList.value || []
  // 搜索过滤
  if (searchKeyword.value) {
    result = result.filter(detail => 
      (detail.product_name || '').toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }
  // 筛选过滤
  if (currentFilter.value.value === 'difference') {
    result = result.filter(detail => detail.inventory_difference_number !== 0)
  } else if (currentFilter.value.value === 'no-difference') {
    result = result.filter(detail => detail.inventory_difference_number === 0)
  }
  return result
})

// 计算可见的明细列表
const visibleDetails = computed(() => {
  return filteredDetails.value.slice(
    startIndex.value,
    startIndex.value + visibleCount
  )
})

// 计算差异数量
const differenceCount = computed(() => {
  return filteredDetails.value.filter(
    detail => detail.inventory_difference_number !== 0
  ).length
})

// 获取盘点明细列表
async function getInventoryDetails() {
  try {
    const res = await uni.request({
      url: IntranetConfig.domain + `api/product/inventory/get_inventory_detail_list/?inventory_id=${inventoryId.value}`,
      method: 'GET',
      header: IntranetConfig.headers
    })
    
    if (res.data.code === 200) {
      detailList.value = res.data.data
    } else {
      throw new Error(res.data.msg)
    }
  } catch (error) {
    showCustomToast(error.message || '获取盘点明细失败', 'error')
  }
}

// 搜索事件
function onSearch() {
  scrollTop.value = 0
  startIndex.value = 0
}

// 筛选事件
function onFilterChange(e) {
  const index = e.detail.value
  currentFilter.value = filterOptions[index]
  scrollTop.value = 0
  startIndex.value = 0
}

// 滚动事件
function onScroll(e) {
  const scrollTop = e.detail.scrollTop
  startIndex.value = Math.floor(scrollTop / itemHeight)
}

// 获取差异文本
function getDifferenceText(difference) {
  if (difference > 0) return `多${difference}个`
  if (difference < 0) return `少${Math.abs(difference)}个`
  return '无差异'
}

// 获取差异样式
function getDifferenceClass(difference) {
  if (difference > 0) return 'difference-positive'
  if (difference < 0) return 'difference-negative'
  return ''
}

// 返回上一页
function onBack() {
  uni.navigateBack()
}

// Toast 相关
const showToast = ref(false)
const toastContent = ref('')
const toastType = ref('')
const toastDuration = ref(2000)

function showCustomToast(content, type = '', duration = 2000) {
  toastContent.value = content
  toastType.value = type
  toastDuration.value = duration
  showToast.value = true
}

// 消息框相关
const showMsgBox = ref(false)
const msgBoxTitle = ref('')
const msgBoxContent = ref('')
const msgBoxShowCancel = ref(true)
const msgBoxConfirmText = ref('确定')
const msgBoxCancelText = ref('取消')
let msgBoxCallback = null

function openMsgBox({ title = '', content = '', showCancel = true, confirmText = '确定', cancelText = '取消', callback = null }) {
  msgBoxTitle.value = title
  msgBoxContent.value = content
  msgBoxShowCancel.value = showCancel
  msgBoxConfirmText.value = confirmText
  msgBoxCancelText.value = cancelText
  msgBoxCallback = callback
  showMsgBox.value = true
}

function onMsgBoxConfirm() {
  if (msgBoxCallback) msgBoxCallback(true)
}

function onMsgBoxCancel() {
  if (msgBoxCallback) msgBoxCallback(false)
}

// 添加明细相关
const showAddDetailPopup = ref(false)
const addDetailForm = ref({
  product: '',
  inventory_number: '',
  inventory_actual_number: '',
  inventory_difference_number: 0,
  inventory_difference_reason: '',
  remark: ''
})
const productList = ref([])
const selectedProduct = ref(null)

// 盘点类型
const inventoryType = ref(1) // 1: 货架, 2: 仓库

async function fetchInventoryType() {
  try {
    const res = await uni.request({
      url: IntranetConfig.domain + 'api/product/inventory/get_inventory/' + inventoryId.value + '/',
      method: 'GET',
      header: IntranetConfig.headers
    })
    if (res.data.code === 200 && res.data.data) {
      inventoryType.value = Number(res.data.data.inventory_type)
    }
  } catch (e) {
    // 可选：错误处理
  }
}

function onInputChange() {
  console.log('Input changed') // 调试日志
  // 自动计算差异数量
  const expect = Number(addDetailForm.value.inventory_number) || 0
  const actual = Number(addDetailForm.value.inventory_actual_number) || 0
  addDetailForm.value.inventory_difference_number = actual - expect
  console.log('Difference calculated:', addDetailForm.value.inventory_difference_number) // 调试日志
  // 差异为0时清空差异原因
  if (addDetailForm.value.inventory_difference_number === 0) {
    addDetailForm.value.inventory_difference_reason = ''
  }
}

// 获取商品列表
async function getProductList() {
  try {
    const res = await uni.request({
      url: IntranetConfig.domain + 'api/product/get_product_list/',
      method: 'GET',
      header: IntranetConfig.headers
    })
    if (res.data.code === 200) {
      productList.value = res.data.data
    }
  } catch (e) {
    showCustomToast('获取商品列表失败', 'error')
  }
}

function onProductChange(e) {
  const index = e.detail.value
  if (!productList.value || !productList.value[index]) return
  selectedProduct.value = productList.value[index]
  if (selectedProduct.value && selectedProduct.value.id) {
    addDetailForm.value.product = selectedProduct.value.id
  }
}

// 添加明细提交
async function onAddDetail() {
  console.log('onAddDetail clicked') // 调试日志
  console.log('Form data:', addDetailForm.value) // 打印表单数据
  console.log('Selected product:', selectedProduct.value) // 打印选中的商品

  // 表单验证
  if (!selectedProduct.value || !addDetailForm.value.product) {
    console.log('Product validation failed') // 调试日志
    showCustomToast('请选择商品', 'error')
    return
  }

  const inventoryNumber = Number(addDetailForm.value.inventory_number)
  if (isNaN(inventoryNumber) || inventoryNumber < 0) {
    console.log('Inventory number validation failed') // 调试日志
    showCustomToast('请输入有效的预计数量', 'error')
    return
  }

  const actualNumber = Number(addDetailForm.value.inventory_actual_number)
  if (isNaN(actualNumber) || actualNumber < 0) {
    console.log('Actual number validation failed') // 调试日志
    showCustomToast('请输入有效的实际数量', 'error')
    return
  }

  const differenceNumber = actualNumber - inventoryNumber
  if (differenceNumber !== 0 && !addDetailForm.value.inventory_difference_reason) {
    console.log('Difference reason validation failed') // 调试日志
    showCustomToast('请填写差异原因', 'error')
    return
  }

  console.log('Form validation passed') // 调试日志
  console.log('Submitting form:', {
    inventory: inventoryId.value,
    product: addDetailForm.value.product,
    inventory_number: inventoryNumber,
    inventory_actual_number: actualNumber,
    inventory_difference_number: differenceNumber,
    inventory_difference_reason: addDetailForm.value.inventory_difference_reason || '',
    remark: addDetailForm.value.remark || ''
  })

  uni.showLoading({ title: '提交中...', mask: true })
  try {
    const requestData = {
      inventory: inventoryId.value,
      product: addDetailForm.value.product,
      inventory_number: inventoryNumber,
      inventory_actual_number: actualNumber,
      inventory_difference_number: differenceNumber,
      inventory_difference_reason: addDetailForm.value.inventory_difference_reason || '',
      remark: addDetailForm.value.remark || ''
    }

    console.log('Sending request with data:', requestData) // 调试日志
    const res = await uni.request({
      url: IntranetConfig.domain + 'api/product/inventory/create_inventory_detail/',
      method: 'POST',
      header: IntranetConfig.headers,
      data: requestData
    })
    
    console.log('Response:', res) // 调试日志
    if (res.data.code === 200) {
      showCustomToast('添加成功', 'success')
      closeAddDetailPopup()
      // 重置表单
      addDetailForm.value = {
        product: '',
        inventory_number: '',
        inventory_actual_number: '',
        inventory_difference_number: 0,
        inventory_difference_reason: '',
        remark: ''
      }
      selectedProduct.value = null
      // 刷新列表
      getInventoryDetails()
    } else {
      throw new Error(res.data.msg || '添加失败')
    }
  } catch (error) {
    console.error('Error:', error) // 调试日志
    showCustomToast(error.message || '添加失败', 'error')
  } finally {
    uni.hideLoading()
  }
}

// 关闭添加明细弹窗
function closeAddDetailPopup() {
  console.log('closeAddDetailPopup called') // 调试日志
  showAddDetailPopup.value = false
  // 重置表单
  addDetailForm.value = {
    product: '',
    inventory_number: '',
    inventory_actual_number: '',
    inventory_difference_number: 0,
    inventory_difference_reason: '',
    remark: ''
  }
  selectedProduct.value = null
}

// 显示添加明细弹窗
function showAddDetail() {
  console.log('showAddDetail called') // 调试日志
  showAddDetailPopup.value = true
  // 重置表单
  addDetailForm.value = {
    product: '',
    inventory_number: '',
    inventory_actual_number: '',
    inventory_difference_number: 0,
    inventory_difference_reason: '',
    remark: ''
  }
  selectedProduct.value = null
}

// 修改添加明细按钮的点击事件
function onAddDetailClick() {
  console.log('Add detail button clicked') // 调试日志
  showAddDetail()
}

// 备注展开/收起逻辑
const expandedRemarkId = ref(null)
function toggleRemark(id) {
  expandedRemarkId.value = expandedRemarkId.value === id ? null : id
}
function getRemarkText(detail) {
  if (!detail.remark) return ''
  if (expandedRemarkId.value === detail.id) return detail.remark
  // 超过20字省略
  return detail.remark.length > 20 ? detail.remark.slice(0, 20) + '...' : detail.remark
}
function shouldShowToggle(detail) {
  return detail.remark && detail.remark.length > 20
}

// 复制主盘点ID
function copyInventoryId() {
  uni.setClipboardData({
    data: inventoryId.value,
    success: () => {
      showCustomToast('主盘点ID已复制', 'success')
    }
  })
}

// 商品选择相关
const showProductSelectPopup = ref(false)
const productSearch = ref('')
const filteredProductList = computed(() => {
  // 获取已添加商品ID集合
  const addedProductIds = new Set((detailList.value || []).map(d => d.product).filter(Boolean))
  // 只显示未被添加过的商品，并支持搜索
  return (productList.value || []).filter(item => {
    if (!item || !item.id) return false
    const notAdded = !addedProductIds.has(item.id)
    const match = !productSearch.value || (item.name || '').toLowerCase().includes(productSearch.value.toLowerCase())
    return notAdded && match
  })
})
function closeProductSelectPopup() {
  showProductSelectPopup.value = false
}
function onSelectProduct(item) {
  if (!item || !item.id) return
  selectedProduct.value = item
  addDetailForm.value.product = item.id
  // 自动填充预计数量
  if (inventoryType.value === 1) {
    addDetailForm.value.inventory_number = item.shelf_number || 0
  } else if (inventoryType.value === 2) {
    addDetailForm.value.inventory_number = item.warehouse_number || 0
  } else {
    addDetailForm.value.inventory_number = 0
  }
  showProductSelectPopup.value = false
  onInputChange() // 触发差异数量自动计算
}

// 明细详情相关
const showDetailPopup = ref(false)
const currentDetail = ref({})
function onShowDetail(detail) {
  currentDetail.value = detail
  showDetailPopup.value = true
}
function closeDetailPopup() {
  showDetailPopup.value = false
}

// 页面加载（兼容App端参数）
onLoad((options) => {
  inventoryId.value = options.id
  if (inventoryId.value) {
    getInventoryDetails()
    getProductList()
    fetchInventoryType()
  }
})
</script>

<style scoped lang="scss">
.inventory-detail-page {
  background: #f8f9fa;
  min-height: 100vh;
  font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
  overflow-x: hidden;
  box-sizing: border-box;
}

.nav-bar {
  display: flex;
  align-items: center;
  padding: 0 32rpx;
  height: 96rpx;
  background: #fff;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 100;
  overflow-x: hidden;
  box-sizing: border-box;
  
  .nav-back { 
    color: #333; 
    font-size: 44rpx;
    width: 80rpx;
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: all 0.3s;
    
    &:active {
      background: rgba(0, 0, 0, 0.05);
    }
  }
  
  .nav-title { 
    flex: 1; 
    text-align: center; 
    font-size: 36rpx;
    font-weight: 600;
    color: #333;
  }

  .action-bar {
    display: flex;
    align-items: center;
    gap: 16rpx;
    margin-left: 16rpx;
  }

  .action-btn {
    background: linear-gradient(90deg, #1890ff 0%, #40a9ff 100%);
    color: #fff;
    border: none;
    border-radius: 16rpx;
    font-size: 26rpx;
    padding: 0 28rpx;
    height: 56rpx;
    display: flex;
    align-items: center;
    box-shadow: 0 2rpx 8rpx rgba(24,144,255,0.12);
    font-weight: 500;
    transition: background 0.2s;
  }

  .action-btn:active {
    background: #1765ad;
  }
}

.main-inventory-id-bar {
  display: flex;
  align-items: center;
  background: #fffbe6;
  border-radius: 16rpx;
  margin: 24rpx 16rpx 0 16rpx;
  padding: 18rpx 24rpx;
  font-size: 28rpx;
  box-shadow: 0 2rpx 8rpx rgba(255, 193, 7, 0.08);
  overflow: hidden;
}
.main-id-label {
  color: #faad14;
  font-weight: 600;
  margin-right: 12rpx;
  flex-shrink: 0;
}
.main-id-value {
  color: #333;
  font-family: 'Consolas', 'Menlo', 'Monaco', monospace;
  font-size: 26rpx;
  max-width: 60vw;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
}
.copy-icon {
  margin-left: 12rpx;
  cursor: pointer;
  transition: color 0.2s;
}
.copy-icon:active {
  color: #1765ad;
}

.search-filter {
  display: flex;
  gap: 16rpx;
  padding: 24rpx 16rpx 24rpx 16rpx;
  background: #fff;
  margin-bottom: 24rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  overflow-x: hidden;
  box-sizing: border-box;
  border-radius: 20rpx;
  
  .search-box {
    flex: 1;
    position: relative;
    display: flex;
    align-items: center;
    background: #f8f9fa;
    border-radius: 12rpx;
    padding: 0 16rpx;
    min-width: 0;
    overflow-x: hidden;
    box-sizing: border-box;
    
    .search-input {
      flex: 1;
      height: 72rpx;
      font-size: 28rpx;
      color: #333;
      margin-left: 12rpx;
      min-width: 0;
      background: transparent;
      border: none;
      
      &::placeholder {
        color: #999;
      }
    }
  }
  
  .filter-box {
    width: 160rpx;
    min-width: 120rpx;
    
    .filter-picker {
      width: 100%;
      height: 72rpx;
      background: #f8f9fa;
      border-radius: 12rpx;
      padding: 0 12rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      box-sizing: border-box;
      
      .picker-value {
        color: #333;
        font-size: 28rpx;
        display: flex;
        align-items: center;
        gap: 8rpx;
        width: 100%;
        overflow: hidden;
      }
    }
  }
}

.statistics {
  display: flex;
  gap: 16rpx;
  padding: 0 16rpx 24rpx 16rpx;
  overflow-x: hidden;
  box-sizing: border-box;
  
  .stat-card {
    flex: 1;
    background: #fff;
    border-radius: 20rpx;
    padding: 32rpx 24rpx;
    display: flex;
    align-items: center;
    gap: 16rpx;
    box-shadow: 0 6rpx 24rpx rgba(0, 0, 0, 0.08);
    min-width: 0;
    overflow-x: hidden;
    box-sizing: border-box;
    
    .stat-icon {
      width: 64rpx;
      height: 64rpx;
      border-radius: 16rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      
      &.total {
        background: #e6f7ff;
      }
      
      &.difference {
        background: #fff1f0;
      }
    }
    
    .stat-content {
      flex: 1;
      min-width: 0;
      
      .stat-value {
        font-size: 36rpx;
        font-weight: 600;
        color: #333;
        display: block;
        margin-bottom: 4rpx;
        
        &.difference {
          color: #ff4d4f;
        }
      }
      
      .stat-label {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}

.detail-list {
  width: 100%;
  max-width: 100vw;
  height: calc(100vh - 360rpx);
  padding: 0 0 0 0;
  overflow-x: hidden;
  box-sizing: border-box;
}

.detail-item {
  margin: 0 16rpx 24rpx 16rpx;
  overflow-x: hidden;
  box-sizing: border-box;
  
  .item-content {
    width: 100%;
    background: #fff;
    border-radius: 20rpx;
    padding: 32rpx 24rpx 24rpx 24rpx;
    box-shadow: 0 6rpx 24rpx rgba(0, 0, 0, 0.08);
    overflow-x: hidden;
    box-sizing: border-box;
    transition: box-shadow 0.2s;
    
    .item-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 18rpx;
      min-width: 0;
      
      .product-info {
        flex: 1;
        margin-right: 16rpx;
        min-width: 0;
        
        .product-name {
          font-size: 32rpx;
          font-weight: 600;
          color: #333;
          display: block;
          margin-bottom: 4rpx;
          word-break: break-all;
          white-space: pre-line;
        }
        
        .product-id {
          font-size: 24rpx;
          color: #999;
          word-break: break-all;
          margin-bottom: 2rpx;
        }
      }
      
      .difference-tag {
        font-size: 24rpx;
        padding: 4rpx 16rpx;
        border-radius: 24rpx;
        white-space: nowrap;
        
        &.difference-positive {
          background: #f6ffed;
          color: #52c41a;
        }
        
        &.difference-negative {
          background: #fff1f0;
          color: #ff4d4f;
        }
      }
    }
    
    .item-info {
      .info-row {
        display: flex;
        gap: 24rpx;
        margin-bottom: 12rpx;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .info-item {
          flex: 1;
          min-width: 0;
          
          &.full-width {
            flex: 2;
          }
          
          .info-label {
            font-size: 24rpx;
            color: #666;
            display: block;
            margin-bottom: 4rpx;
            word-break: break-all;
          }
          
          .info-value {
            font-size: 28rpx;
            color: #333;
            font-weight: 500;
            word-break: break-all;
            
            &.reason {
              font-weight: normal;
              color: #666;
            }
            &.remark-ellipsis {
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
              display: inline-block;
              max-width: 70vw;
              cursor: pointer;
              vertical-align: bottom;
            }
            &.remark-ellipsis.expanded {
              white-space: pre-line;
              overflow: visible;
              text-overflow: initial;
              display: block;
              background: #f8f9fa;
              border-radius: 8rpx;
              padding: 8rpx 12rpx;
              margin-top: 4rpx;
            }
            .remark-toggle {
              color: #1890ff;
              font-size: 24rpx;
              margin-left: 8rpx;
              cursor: pointer;
            }
          }
        }
      }
    }
  }
}

.custom-popup-mask {
  position: fixed;
  left: 0; top: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.25);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}
.custom-popup-box {
  width: 600rpx;
  background: #fff;
  border-radius: 24rpx;
  overflow: hidden;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.12);
  animation: popup-fade-in 0.2s;
}
@keyframes popup-fade-in {
  from { transform: scale(0.95); opacity: 0; }
  to { transform: scale(1); opacity: 1; }
}
.popup-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx;
  border-bottom: 1rpx solid #f5f5f5;
  background: #fff;
}
.popup-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}
.popup-content {
  padding: 32rpx;
  background: #fff;
}
.form-row {
  display: flex;
  align-items: center;
  margin-bottom: 24rpx;
}
.form-label {
  width: 140rpx;
  color: #333;
  font-size: 28rpx;
}
.form-input {
  flex: 1;
  border: none;
  background: #f8f9fa;
  border-radius: 12rpx;
  padding: 16rpx;
  font-size: 28rpx;
  color: #333;
}
.picker-value {
  color: #333;
  font-size: 28rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
  padding: 16rpx;
  margin-bottom: 24rpx;
}
.popup-footer {
  padding: 24rpx 32rpx;
  border-top: 1rpx solid #f5f5f5;
  background: #fff;
  display: flex;
  gap: 24rpx;
}
.confirm-btn {
  flex: 1;
  height: 88rpx;
  background: #1890ff;
  color: #fff;
  border: none;
  border-radius: 12rpx;
  font-size: 32rpx;
  font-weight: 500;
  transition: all 0.3s;
}
.confirm-btn:active {
  background: #1765ad;
}
.cancel-btn {
  flex: 1;
  height: 88rpx;
  background: #f5f5f5;
  color: #333;
  border: none;
  border-radius: 12rpx;
  font-size: 32rpx;
  font-weight: 500;
  transition: all 0.3s;
}
.cancel-btn:active {
  background: #e0e0e0;
}

.select-btn {
  display: flex;
  align-items: center;
  background: #f8f9fa;
  border-radius: 12rpx;
  padding: 0 16rpx;
  min-height: 64rpx;
  cursor: pointer;
  font-size: 28rpx;
  color: #333;
  width: 100%;
  box-sizing: border-box;
}
.select-btn .placeholder {
  color: #bbb;
}
.product-popup-box {
  width: 650rpx;
  background: #fff;
  border-radius: 28rpx;
  overflow: hidden;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.12);
  animation: popup-fade-in 0.2s;
}
.product-search-bar {
  display: flex;
  align-items: center;
  background: #f4f6fa;
  border-radius: 24rpx;
  border: 2rpx solid #e6eaf0;
  padding: 0 32rpx;
  margin-bottom: 28rpx;
  height: 80rpx;
  box-sizing: border-box;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.03);
}
.search-icon {
  margin-right: 18rpx;
}
.product-search-input {
  flex: 1;
  background: transparent;
  border: none;
  font-size: 32rpx;
  color: #333;
  height: 80rpx;
  line-height: 80rpx;
  outline: none;
}
.product-list-scroll {
  max-height: 600rpx;
  overflow-y: auto;
}
.product-item-big {
  display: flex;
  align-items: center;
  gap: 32rpx;
  padding: 32rpx 32rpx;
  border-bottom: 1rpx solid #f0f0f0;
  cursor: pointer;
  transition: background 0.2s;
  min-height: 120rpx;
}
.product-item-big:active {
  background: #f5f5f5;
}
.product-img {
  width: 96rpx;
  height: 96rpx;
  border-radius: 16rpx;
  object-fit: cover;
  background: #f8f9fa;
  display: flex;
  align-items: center;
  justify-content: center;
}
.product-img-placeholder {
  background: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
}
.product-name-big {
  font-size: 34rpx;
  font-weight: 600;
  color: #333;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.no-result {
  text-align: center;
  color: #bbb;
  padding: 32rpx 0;
}

.selected-product-name {
  color: #1890ff;
  font-weight: 600;
  font-size: 30rpx;
  margin-right: 4rpx;
}

.detail-popup-box {
  width: 600rpx;
  background: #fff;
  border-radius: 24rpx;
  overflow: hidden;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.12);
  animation: popup-fade-in 0.2s;
}
.detail-popup-content {
  padding: 32rpx;
  background: #fff;
}
.detail-row {
  display: flex;
  align-items: flex-start;
  margin-bottom: 24rpx;
}
.detail-label {
  color: #888;
  font-size: 28rpx;
  width: 160rpx;
  flex-shrink: 0;
}
.detail-value {
  color: #333;
  font-size: 28rpx;
  word-break: break-all;
}

/* 添加Toast相关样式 */
:deep(.toast-container) {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 99999;
  pointer-events: none;
  animation: toast-fade-in 0.3s ease-out;
}

:deep(.toast-content) {
  background: #fff;
  color: #333;
  padding: 24rpx 48rpx;
  border-radius: 16rpx;
  font-size: 30rpx;
  text-align: center;
  max-width: 80vw;
  min-width: 120rpx;
  min-height: 88rpx;
  line-height: 1.5;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);
  border: 1px solid #e6e6e6;
  display: flex;
  align-items: center;
  justify-content: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  pointer-events: none;
}

:deep(.toast-content.success) {
  color: #52c41a;
}

:deep(.toast-content.error) {
  color: #ff4d4f;
}

:deep(.toast-content.warning) {
  color: #faad14;
}

@keyframes toast-fade-in {
  from {
    opacity: 0;
    transform: translate(-50%, -40%);
  }
  to {
    opacity: 1;
    transform: translate(-50%, -50%);
  }
}

@keyframes toast-fade-out {
  from {
    opacity: 1;
    transform: translate(-50%, -50%);
  }
  to {
    opacity: 0;
    transform: translate(-50%, -60%);
  }
}

/* 确保弹窗的z-index低于Toast */
.custom-popup-mask {
  z-index: 999;
}

.custom-popup-box {
  z-index: 1000;
}

/* 确保其他弹窗的z-index也低于Toast */
</style> 